import axios from 'axios';
import router from '../router/index';
import { Toast, Dialog } from 'vant';
import 'vant/lib/dialog/style/less';
import 'vant/lib/toast/style/less';

const instance = axios.create();
instance.defaults.baseURL = 'http://192.168.43.117:3000';
instance.defaults.timeout = 8000;

// 请求封装
instance.interceptors.request.use(
    config => {
        const token = localStorage.getItem('token');
        token && (config.headers.Authorization = token);
        return config;
    },
    error => Promise.reject(error)
);

// 响应封装
instance.interceptors.response.use(
    response => {
        Toast.clear();
        if (response.status === 200) {
            return Promise.resolve(response.data);
        } else {
            return Promise.reject(response);
        }
    },
    error => {
        if (error.response) {
            switch (error.response.status) {
                // 401未登录
                case 401:
                    router.replace({
                        path: '/profile/login'
                    });
                    break;
                case 403: {
                    // 身份过期
                    localStorage.removeItem('token');
                    localStorage.removeItem('id');
                    Dialog.confirm({
                        message: '用户信息已过期，请尝试重新登录'
                    })
                        .then(() => {
                            router.replace({ name: 'login' });
                        })
                        .catch(() => {
                            // eslint-disable-next-line prefer-promise-reject-errors
                            return Promise.reject(false);
                        });
                }
            }
        } else {
            Toast.fail({
                message: '请求超时，连接服务器失败！',
                forbidClick: true,
                duration: 1500
            });
        }
        console.log(error);
        return Promise.reject(error.response.data || error);
    }
);

export default {
    instance,
    axios
};
